<template>
  <div>
    <div class="content">
      <el-form
        style="width: 700px"
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
      >
        <el-form-item label="选择位置" prop="address">
          <div
            id="container"
            style="width: 100%; height: 200px; border: 1px solid gray"
          ></div>
        </el-form-item>
        <el-form-item label="姓名" prop="aname">
          <el-input v-model="form.aname" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入收货人电话" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input v-model="form.province" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="form.city" />
        </el-form-item>
        <el-form-item label="地区" prop="district">
          <el-input v-model="form.district" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="form.address"
            placeholder="请输入详细地址，如道路、门牌号、小区、楼栋、单元等信息"
          />
        </el-form-item>
        <el-checkbox v-model="form.default_address" class="address"
          >设置为默认收货地址</el-checkbox
        >
        <el-form-item>
          <el-button @click="submit" type="primary">新增收货地址</el-button>
          <el-button @click="result('form')" type="info">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
export default {
  data() {
    return {
      tableData: [],
      tags: [], // 保存所有的标签
      map: null, // 保存地图对象
      marker: null, // 当前选中的坐标点
      form: {
        aname: "",
        phone: "",
        province: "",
        city: "",
        district: "",
        address: "",
        postalCode: "", //邮编
        default_address: "",
      },
      rules: {
        name: [{ required: true, message: "必填", trigger: "blur" }],
        phone: [{ required: true, message: "必填", trigger: "blur" }],
        province: [{ required: true, message: "必填", trigger: "blur" }],
        city: [{ required: true, message: "必填", trigger: "blur" }],
        district: [{ required: true, message: "必填", trigger: "blur" }],
        address: [{ required: true, message: "必填", trigger: "blur" }],
        postalCode: [{ required: false, message: "必填", trigger: "blur" }],
      },
    };
  },

  /** 页面挂载完毕后，加载地图*/
  mounted() {
    // 加载地图
    window._AMapSecurityConfig = {
      securityJsCode: "a61913657c46b57a5776f015802aaa39",
    };
    AMapLoader.load({
      // 申请好的Web端开发者Key，首次调用 load 时必填
      key: "62ede3ec791c821a082ca3cee3747a80",
      version: "2.0", // 指定要加载的 JSAPI 的版本
      plugins: ["AMap.Geocoder"], // 需要使用的的插件列表
    })
      .then((AMap) => {
        this.map = new AMap.Map("container");
        this.map.setCenter([116.403016, 39.93729]);
        this.map.setZoom(13);
        // 为地图绑定事件
        this.map.on("click", (ev) => {
          let { lng, lat } = ev.lnglat;
          console.log({ lng, lat });
          // 添加一个点标记
          if (this.marker) {
            this.marker.setPosition([lng, lat]);
          } else {
            this.marker = new AMap.Marker({
              position: [lng, lat],
            });
            this.map.add(this.marker);
          }
          // 通过该经纬度，获取对应的详细位置字符串描述
          // 需要访问高德地图的web服务
          this.getAddress(AMap, [lng, lat]);
        });
      })
      .catch((e) => {
        console.log(e);
      });
  },
  methods: {
    result(form) {
      this.$refs["form"].resetFields();
    },
    //点击提交表单
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let user = sessionStorage.getItem("user");
          user = JSON.parse(user);
          let { uid } = user;
          let { aname, phone, address, default_address } = this.form;
          let params = { uid, aname, phone, default_address, address };
          this.$http.addressApi.add(params).then((res) => {
            // console.log(res);
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "新增收货地址",
              });
            }
          });
        }
      });
    },

    // 通过position经纬度，使用AMap.Geocoder插件
    // 完成逆地理查询
    getAddress(AMap, position) {
      let geocoder = new AMap.Geocoder();
      geocoder.getAddress(position, (status, result) => {
        console.log(status, result);
        // 回填表单字段
        let r = result.regeocode;
        this.form.address = r.formattedAddress;
        this.form.province = r.addressComponent.province;
        this.form.city = r.addressComponent.city || r.addressComponent.province;
        this.form.district = r.addressComponent.district;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  padding: 20px;
  h4 {
    margin-bottom: 10px;
  }
  .address {
    margin: 10px 80px 20px;
  }
  .address-table {
    margin-top: 20px;
    padding: 50px;
  }
}
</style>
